/*
 * BanBu_DetailEmoViewController
 * @description 本文件提供表情商店具体表情的界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供表情商店具体表情的界面的ViewController
 */

#import "BanBu_DetailEmoViewController.h"
#import "UIImage+emoImage.h"
#import "UIImageView+WebCache.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"

@interface BanBu_DetailEmoViewController ()

@end

@implementation BanBu_DetailEmoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = [_emoInfoDic valueForKey:KeyName];
    _mainScrolView.userInteractionEnabled = YES;
    
    if (__MainScreen_Height < 500)
    {
        [_mainScrolView setContentSize:CGSizeMake(320, 600)];
    }
    
    _DetailView.layer.cornerRadius = 6;
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"chatbg.jpg"]];
    
    _showBigView.hidden = YES;
    [self.view addSubview:_showBigView];
    
    _longPressLabel.text = NSLocalizedString(@"longPressToView", nil);
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadView) name:KFinishDownloadingEmo object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [self initView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    [_emoInfoDic release],_emoInfoDic = nil;
    [_mainScrolView release];
    [_faceImage release];
    [_nameLabel release];
    [_feeStateLabel release];
    [_downloadBtn release];
    [_introductionText release];
    [_emoScrolView release];
    [_DetailView release];
    [_pageControl release];
    [_BigView release];
    [_showBigView release];
    [_backgroundImageView release];
    [_emoProgress release];
    [_longPressLabel release];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:KFinishDownloadingEmo object:nil];
    [_actorIndicator release];
    [super dealloc];
}

- (void)viewDidUnload
{
    [self setMainScrolView:nil];
    [self setFaceImage:nil];
    [self setNameLabel:nil];
    [self setFeeStateLabel:nil];
    [self setDownloadBtn:nil];
    [self setIntroductionText:nil];
    [self setEmoScrolView:nil];
    [self setDetailView:nil];
    [self setPageControl:nil];
    [self setBigView:nil];
    [self setShowBigView:nil];
    [self setBackgroundImageView:nil];
    [self setEmoProgress:nil];
    [self setLongPressLabel:nil];
    [super viewDidUnload];
}

-(void)initView
{
    //查缓存，没有缓存时下载并显示
    NSString * imageName = @"icon.png";
    NSString * imageUrl = [NSString stringWithFormat:@"%@%@",[_emoInfoDic valueForKey:KeyPath],imageName];
    
    [_faceImage setImageWithUrlString:imageUrl withFolderName:[AppComManager remove_:[_emoInfoDic valueForKeyPath:Keyid]] withImageName:imageName];
    
    _nameLabel.text = [_emoInfoDic valueForKey:KeyName];
    
    //免费、付费
    if ([[_emoInfoDic valueForKey:KeyFeeState] boolValue])
    {
        _feeStateLabel.text = [_emoInfoDic valueForKey:KeyFee];
    }
    else
    {
        _feeStateLabel.text = @"free";
    }
    
    //简介
    _introductionText.text = [_emoInfoDic valueForKey:KeyContent1];
    _introductionText.backgroundColor = [UIColor clearColor];
    _introductionText.font = [UIFont systemFontOfSize:16];
    
    [self reloadView];
    
    //下载所有缩略图
    [self initEmoScrolView:[[_emoInfoDic valueForKey:KeyCount] integerValue]];
}


//初始化缩略图
-(void)initEmoScrolView:(NSInteger)imagCount
{
    _emoScrolView.contentSize = CGSizeMake(320*ceilf(imagCount/8.0), 216);
    _emoScrolView.pagingEnabled = YES;
    _pageControl.numberOfPages = ceilf(imagCount/8.0);
    
    CGRect frame = CGRectZero;
    NSInteger page = 0;
    for (int i = 0;i<imagCount;i++)
    {
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
        frame = imageView.frame;
        frame.origin.x = 76*(i%4) + page*320 +16;
        frame.origin.y = 90*((i-page*8)/4)+10;
        imageView.frame = frame;
        
        imageView.userInteractionEnabled = YES;
        imageView.backgroundColor = [UIColor clearColor];
        imageView.tag = 10001+i;
        
        //添加手势
        UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(showBigImage:)];
        [imageView addGestureRecognizer:longPress];
        [longPress release];
        
        //查缓存，没有缓存时下载并显示
        NSString * imageName = [NSString stringWithFormat:@"%d.jpg",i+1];
        NSString * imageUrl = [NSString stringWithFormat:@"%@%@",[_emoInfoDic valueForKey:KeyPath],imageName];
        
        [imageView setImageWithUrlString:imageUrl withFolderName:[AppComManager remove_:[_emoInfoDic valueForKeyPath:Keyid]] withImageName:imageName];
        
        [_emoScrolView addSubview:imageView];
        if ((i+1)%8==0)
        {
            page += 1;
        }
    }
}

//设置下载按钮
-(void)reloadView
{
    //本地下载文件
    NSDictionary * downloadEmoInfoDic = [NSKeyedUnarchiver unarchiveObjectWithFile:DownloadInfoPath];
    downloadEmoInfoDic = [downloadEmoInfoDic valueForKey:[_emoInfoDic valueForKey:Keyid]];
    _downloadBtn.enabled = YES;
    _downloadBtn.hidden = NO;
    
    _emoProgress.hidden = YES;
    
    //设置下载按钮
    if ([[downloadEmoInfoDic valueForKey:KeyDownloadState] boolValue])//已下载
    {
        [_downloadBtn setBackgroundImage:[UIImage imageNamed:@"btn_emo_downloaded.png"] forState:UIControlStateNormal];
        [_downloadBtn setTitle:NSLocalizedString(@"haveDownload", nil) forState:UIControlStateNormal];
        _btnType = ButtonTypeDownloaded;//已下载
        _downloadBtn.enabled = NO;
    }
    else if ([[_emoInfoDic valueForKey:KeyFeeState] boolValue])//付费表情
    {
        if ([[_emoInfoDic valueForKey:KeyPayState] boolValue])//已付费
        {
            [_downloadBtn setBackgroundImage:[UIImage imageNamed:@"btn_emo_download.png"] forState:UIControlStateNormal];
            [_downloadBtn setTitle:nil forState:UIControlStateNormal];
            _btnType = ButtonTypeDownload;//可下载
        }
        else//未付费
        {
            [_downloadBtn setBackgroundImage:[UIImage imageNamed:@"btn_emo_download_bg.png"] forState:UIControlStateNormal];
            [_downloadBtn setTitle:NSLocalizedString(@"sale", nil) forState:UIControlStateNormal];
            _btnType = ButtonTypeFee;//未付费
        }
    }
    else//免费表情，未下载
    {
        [_downloadBtn setBackgroundImage:[UIImage imageNamed:@"btn_emo_download_bg.png"] forState:UIControlStateNormal];
        [_downloadBtn setTitle:NSLocalizedString(@"free", nil) forState:UIControlStateNormal];
        _btnType = ButtonTypeFree;//可下载
    }
}

#pragma mark -  ScrollViewDelagate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _pageControl.currentPage = scrollView.contentOffset.x/320.0;
}

//下载按钮事件处理
- (IBAction)download:(UIButton *)sender
{
    switch (_btnType)
    {
        case ButtonTypeDownload:
        case ButtonTypeFree://免费表情
        {
            //点击下载表情
            NSString * emoUrl = [NSString stringWithFormat:@"%@zip.zip",[_emoInfoDic valueForKey:KeyPath]];
            
            _downloadBtn.hidden = YES;
            _emoProgress.hidden = NO;
            [AppComManager downLoadEmoWithUrl:emoUrl withEmoInfoDic:_emoInfoDic delegate:self];
        }
            break;
            
        case ButtonTypeFee://付费
        {
            //去付费
            
        }
            break;
        default:
            break;
    }
}


//下载进度
-(void)setProgress:(float)newProgress
{
    _emoProgress.progress = newProgress;
}

//长按缩略图时显示大图
-(void)showBigImage:(UILongPressGestureRecognizer *)gesture
{
    //先判断点的是哪个缩略图
    CGPoint locationPoint = [gesture locationInView:_emoScrolView];
    NSInteger x = (int)locationPoint.x %320;
    NSInteger y = locationPoint.y;
    NSInteger tagIndex = 10001;
    
    if (x < 75)//第一列
    {
        x = 10 +100;//100是大图的宽的一半，x，y是大图的中心点坐标
        tagIndex += _pageControl.currentPage*8;
    }
    else if (x<92+60)//第二列
    {
        x = 22 +100;
        tagIndex += _pageControl.currentPage*8 + 1;
    }
    else if (x< 168+60)//第三列
    {
        x = 98 +100;
        tagIndex += _pageControl.currentPage*8 + 2;
    }
    else//第四列
    {
        x = 110 +100;
        tagIndex += _pageControl.currentPage*8 + 3;
    }
    
    if (y<70)//第一行
    {
        y = 210;
    }
    else//第二行
    {
        y = 310;
        tagIndex += 4;
    }
    
    if (x <= 110)//在左边时
    {
        _backgroundImageView.image = [UIImage imageNamed:@"emo_showBackground_left.png"];
    }
    else if (x >= 210)//
    {
        _backgroundImageView.image = [UIImage imageNamed:@"emo_showBackground_right.png"];
    }
    else
    {
        _backgroundImageView.image = [UIImage imageNamed:@"emo_showBackground_middle.png"];
    }
    
    if (((int)_showBigView.center.x != x) || ((int)_showBigView.center.y != y))
    {
        //去下载大图
        _showBigView.center = CGPointMake(x, y);
        NSString * imageName = [NSString stringWithFormat:@"%d.gif",tagIndex-10000];
        NSString * imageUrl = [NSString stringWithFormat:@"%@%@",[_emoInfoDic valueForKey:KeyPath],imageName];
        if ([FileManager fileExistsAtPath:[AppComManager pathForEmo:imageName withFolder:[AppComManager remove_:[_emoInfoDic valueForKeyPath:Keyid]]]])
        {
            [self.actorIndicator stopAnimating];
            self.actorIndicator.hidden = YES;
        }
        else
        {
            [self.actorIndicator stopAnimating];
            self.actorIndicator.hidden = YES;
        }
        [_BigView setImageWithUrlString:imageUrl withFolderName:[AppComManager remove_:[_emoInfoDic valueForKeyPath:Keyid]] withImageName:imageName];
    }
    
    switch (gesture.state)
    {
        case UIGestureRecognizerStateBegan:
        {
            _showBigView.hidden = NO;
        }
            break;
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateCancelled:
        {
            [_BigView setImageWithURL:nil];
            _BigView.gifFile = nil;
            _showBigView.hidden = YES;
            gesture.view.backgroundColor = [UIColor clearColor];
        }
        default:
            break;
    }
}
@end
